package com.hmall.search.service.impl;

import com.alibaba.fastjson.JSON;
import com.hmall.common.dto.PageDTO;
import com.hmall.common.pojo.ItemDoc;
import com.hmall.common.pojo.RequestItems;
import com.hmall.search.service.SearchService;
import org.apache.commons.lang.StringUtils;
import org.elasticsearch.action.search.SearchRequest;
import org.elasticsearch.action.search.SearchResponse;
import org.elasticsearch.client.RequestOptions;
import org.elasticsearch.client.RestHighLevelClient;
import org.elasticsearch.index.query.AbstractQueryBuilder;
import org.elasticsearch.index.query.BoolQueryBuilder;
import org.elasticsearch.index.query.QueryBuilders;
import org.elasticsearch.index.query.functionscore.FunctionScoreQueryBuilder;
import org.elasticsearch.index.query.functionscore.ScoreFunctionBuilders;
import org.elasticsearch.search.SearchHit;
import org.elasticsearch.search.SearchHits;
import org.elasticsearch.search.aggregations.AggregationBuilders;
import org.elasticsearch.search.aggregations.Aggregations;
import org.elasticsearch.search.aggregations.bucket.terms.Terms;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightBuilder;
import org.elasticsearch.search.fetch.subphase.highlight.HighlightField;
import org.elasticsearch.search.sort.SortOrder;
import org.elasticsearch.search.suggest.Suggest;
import org.elasticsearch.search.suggest.SuggestBuilder;
import org.elasticsearch.search.suggest.SuggestBuilders;
import org.elasticsearch.search.suggest.completion.CompletionSuggestion;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import org.springframework.util.CollectionUtils;

import java.io.IOException;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@Service("searchService")
public class SearchServiceImpl implements SearchService {
    @Autowired
    private RestHighLevelClient client;

    @Override
    public List<String> getSuggestionList(String key) {
        try {
            //创建request对象
            SearchRequest request = new SearchRequest("item");
            //准备DSL查询条件
            request.source().suggest(
                    new SuggestBuilder().addSuggestion("suggestions",
                            SuggestBuilders.completionSuggestion("suggestion")
                                    .prefix(key)
                                    .skipDuplicates(true)//过滤重复项
                                    .size(10)
                    )
            );
            //发起请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            //解析结果
            Suggest suggest = response.getSuggest();
            //获取对应的补全结果
            CompletionSuggestion suggestions = suggest.getSuggestion("suggestions");

            // 4.2.获取options
            List<CompletionSuggestion.Entry.Option> options = suggestions.getOptions();
            // 4.3.遍历
            List<String> list = new ArrayList<>(options.size());
            for (CompletionSuggestion.Entry.Option option : options) {
                String text = option.getText().toString();
                list.add(text);
            }
            return list;

        } catch (Exception e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
    }

    @Override
    public Map<String, List<String>> filters(RequestItems requestItems) {
        try {
            // 1.准备Request
            SearchRequest request = new SearchRequest("item");
            // 2.准备DSL
            // 2.1.设置query条件
            queryBuilder(requestItems, request);
            // 2.2.设置size
            request.source().size(0);
            // 2.3.聚合
            buildAggregation(request);
            // 3.发出请求
            SearchResponse response = client.search(request, RequestOptions.DEFAULT);
            // 4.解析结果
            Map<String, List<String>> result = new HashMap<>();
            Aggregations aggregations = response.getAggregations();
            // 4.1.根据品牌名称，获取品牌结果
            List<String> brandList = getAggByName(aggregations, "brandAgg");
            result.put("brand", brandList);
            // 4.2.根据分类，获取分类结果
            List<String> categoryList = getAggByName(aggregations, "categoryAgg");
            result.put("category", categoryList);

            return result;
        } catch (IOException e) {
            throw new RuntimeException(e);
        }
    }

    @Override
    public PageDTO<ItemDoc> getItems(RequestItems requestItems) {

        SearchRequest request = new SearchRequest("item");
        AbstractQueryBuilder abstractQueryBuilder = queryBuilder(requestItems, request);
        request.source().query(abstractQueryBuilder);

        //实现分页操作
        int size = requestItems.getSize();
        int currentPage = requestItems.getPage();
        request.source().from((currentPage - 1) * size).size(size);

        //发送查询参数并获取响应结果
        SearchResponse response;
        try {
            response = client.search(request, RequestOptions.DEFAULT);
        } catch (IOException e) {
            e.printStackTrace();
            throw new RuntimeException(e);
        }
        //解析响应结果并将解析结果返回
        return handleResponse(response);
    }

    //构建分桶
    private void buildAggregation(SearchRequest request) {
        request.source().aggregation(AggregationBuilders
                .terms("brandAgg")
                .field("brand")
                .size(100)//最大分组数量
        );
        request.source().aggregation(AggregationBuilders
                .terms("categoryAgg")
                .field("category")
                .size(100)
        );
    }

    //聚合数据
    private List<String> getAggByName(Aggregations aggregations, String aggName) {
        // 4.1.根据聚合名称获取聚合结果
        Terms brandTerms = aggregations.get(aggName);
        // 4.2.获取buckets
        List<? extends Terms.Bucket> buckets = brandTerms.getBuckets();
        // 4.3.遍历
        List<String> brandList = new ArrayList<>();
        for (Terms.Bucket bucket : buckets) {
            // 4.4.获取key
            String key = bucket.getKeyAsString();
            brandList.add(key);
        }
        return brandList;
    }

    /**
     * 用于构建查询条件对象
     *
     * @return
     */
    private AbstractQueryBuilder queryBuilder(RequestItems requestItems, SearchRequest request) {
        BoolQueryBuilder queryBuilder = QueryBuilders.boolQuery();

        //查询名字
        if (StringUtils.isNotBlank(requestItems.getKey()))
            queryBuilder.must(QueryBuilders.matchQuery("all", requestItems.getKey()));
        else
            queryBuilder.must(QueryBuilders.matchAllQuery());

        //查询分类
        if (StringUtils.isNotBlank(requestItems.getCategory()))
            queryBuilder.filter(QueryBuilders.termQuery("category", requestItems.getCategory()));

        //查询品牌
        if (StringUtils.isNotBlank(requestItems.getBrand()))
            queryBuilder.filter(QueryBuilders.termQuery("brand", requestItems.getBrand()));

        //查询价格
        Integer minPrice = requestItems.getMinPrice();
        Integer maxPrice = requestItems.getMaxPrice();

        //防止传入超大数
        if (maxPrice != null && String.valueOf(maxPrice).length() >= 6)
            maxPrice = null;

        if (maxPrice != null && minPrice != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100).lte(maxPrice * 100));
        } else if (maxPrice != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").lte(maxPrice * 100));
        } else if (minPrice != null) {
            queryBuilder.filter(QueryBuilders.rangeQuery("price").gte(minPrice * 100));
        }


        //设置关键字高亮
        request.source().highlighter(new HighlightBuilder().field("name").requireFieldMatch(false));

        if (requestItems.getSortBy() != null) {
            if (requestItems.getSortBy().equals("price"))
                request.source().sort("price", SortOrder.ASC);
            else if (requestItems.getSortBy().equals("score"))
                request.source().sort("score", SortOrder.ASC);
        }
        //竞价排名
        FunctionScoreQueryBuilder functionScoreQuery = QueryBuilders.functionScoreQuery(
                queryBuilder,
                new FunctionScoreQueryBuilder.FilterFunctionBuilder[]{
                        new FunctionScoreQueryBuilder.FilterFunctionBuilder(
                                QueryBuilders.termQuery("isAD", true),
                                ScoreFunctionBuilders.weightFactorFunction(10)
                        )
                }
        );
        request.source().query(functionScoreQuery);

        return functionScoreQuery;
    }

    /**
     * 用于解析Es响应的结果
     *
     * @return 解析后的响应结果对象
     */
    private PageDTO<ItemDoc> handleResponse(SearchResponse response) {
        //获取结果对象
        SearchHits hits = response.getHits();

        //获取总命中数
        long total = hits.getTotalHits().value;
        //获取命中结果数组
        SearchHit[] searchHits = hits.getHits();

        ArrayList<ItemDoc> docArrayList = new ArrayList<>();
        //遍历结果数组
        for (SearchHit searchHit : searchHits) {
            //将Json字符串转为ItemDoc对象
            String sourceAsString = searchHit.getSourceAsString();
            ItemDoc itemDoc = JSON.parseObject(sourceAsString, ItemDoc.class);

            //获取高亮Map集合
            Map<String, HighlightField> highlightFields = searchHit.getHighlightFields();
            //如果不为空,则进行高亮处理并重新写入name
            if (!CollectionUtils.isEmpty(highlightFields)) {
                HighlightField highlightField = highlightFields.get("name");
                if (highlightField != null) {
                    itemDoc.setName(highlightField.getFragments()[0].string());
                }
            }

            docArrayList.add(itemDoc);
        }

        return new PageDTO<>(total, docArrayList);
    }
}
